package _interview150;

import java.util.List;

/**
 * 139. 单词拆分
 */
public class No139 {
    private String s;
    private List<String> wordDict;

    /**
     * 1. 递归
     */
    public boolean wordBreak1(String s, List<String> wordDict) {
        this.s = s;
        this.wordDict = wordDict;
        return dfs(s.length() - 1, s.length());
    }

    private boolean dfs(int i, int j) {
        if (i < 0) return j == 0;
        if (!wordDict.contains(s.substring(i, j))) return dfs(i - 1, j);
        return dfs(i - 1, j) || dfs(i - 1, i);
    }

    /**
     * 2. 迭代
     */
    public boolean wordBreak2(String s, List<String> wordDict) {
        int n = s.length();
        boolean[][] f = new boolean[n + 1][n + 1];
        f[0][0] = true;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n + 1; j++) {
                if (!wordDict.contains(s.substring(i, j))) f[i + 1][j] = f[i][j];
                else f[i + 1][j] = f[i][j] || f[i][i];
            }
        }
        return f[n][n];
    }

    /**
     * 4. 一维数组
     */
    public boolean wordBreak4(String s, List<String> wordDict) {
        int n = s.length();
        boolean[] f = new boolean[n + 1];
        f[0] = true;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n + 1; j++) {
                if (wordDict.contains(s.substring(i, j))) f[j] |= f[i];
            }
        }
        return f[n];
    }
}
